<?php
/**
 * Created by PhpStorm.
 * User: 9ey
 * Date: 2019/5/19
 * Time: 18:12
 */

namespace App\Utils;


use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;

class ApiLog
{
    /**
     * 写入日志
     * @param string $fileName 文件名字
     * @param string $data 写入内容
     */
    static function info($fileName, $data)
    {
        self::write($fileName, "\r\n{$data}");
    }

    /**
     * 写入日志
     * @param string $fileName 文件名字
     * @param string $data 写入内容
     */
    static function write($fileName, $data)
    {
        try {
            $dir = storage_path('logs/' . date('ymd'));
            try {
                self::create_dir($dir);
            } catch (\Exception $e) {

            }
            $file = $dir . '/' . $fileName . '.log';
            $time = date('H:i:s');
            Log::useFiles($file);
            Log::info("[{$time}]{$data}\r\n\r\n");
            chmod($file, 0777);
        } catch (\Exception $e) {
            //echo $e->getMessage()."\n".$e->getTraceAsString();
        }
    }

    /**
     * 写入日志
     * @param string $fileName 文件名字
     * @param string $data 写入内容
     */
    static function api($data)
    {
        $request = \request();
        $uri = $request->path();
        $pathInfo = (explode('/', $uri));
        if (count($pathInfo) == 3) {
            $action = $pathInfo[1] . '_' . $pathInfo[2];
        } else if (count($pathInfo) < 3) {
            $action = $pathInfo[1];
        } else {
            $action = 'other';
        }
        $uri = Request::path();
        $ip = $request->getClientIp();
        self::write($action, "[{$ip}] [{$uri}]\r\n{$data}");
    }

    /**
     * 写入日志
     * @param string $fileName 文件名字
     * @param string $data 写入内容
     */
    static function create_dir($dir, $mode = 0777)
    {
        return is_dir($dir) or (self::create_dir(dirname($dir)) and mkdir($dir, $mode));
    }
}